/**
 * @author        方珂琛 <984512789@qq.com>
 * @date          2023-09-06 11:47:37
 * Copyright © 宁波舟山港舟山港务有限公司 All rights reserved
 */
import { dialog } from "electron";
import logger from "electron-log";
import { autoUpdater } from "electron-updater";

export const useAutoUpdater = () => {
  logger.transports.file.maxSize = 1002430;
  logger.transports.file.format =
    "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}";
  logger.transports.file.resolvePath = () => "./operation.log";

  autoUpdater.checkForUpdates();
  autoUpdater.autoDownload = false;
  autoUpdater.on("error", (error) => {
    logger.error(["检查更新失败", error]);
  });
  autoUpdater.on("update-available", (info) => {
    logger.info("检查到有更新，开始下载新版本");
    autoUpdater.downloadUpdate();
  });
  autoUpdater.on("update-not-available", () => {
    logger.info("没有可用更新");
  });
  autoUpdater.on("update-downloaded", (res) => {
    logger.info("下载完毕！提示安装更新");
    dialog
      .showMessageBox({
        title: "升级提示！",
        message: "已为您下载最新应用，点击确定马上替换为最新版本！",
      })
      .then((index) => {
        logger.info("退出应用，安装开始！");
        autoUpdater.quitAndInstall();
      });
  });
};
